package io.rong.app.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.yunshipei.base.BaseActivity;
import com.yunshipei.base.BaseSubscriberAdapter;
import com.yunshipei.common.net.HttpMethods;
import com.yunshipei.common.wedigt.YspTitleBar;
import com.yunshipei.db.DatabaseUtil;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.ClearGroupNumber;
import com.yunshipei.model.EventModelObject;
import com.yunshipei.model.HeadName;
import com.yunshipei.ui.activity.SeekContactsActivity;
import com.yunshipei.ui.dialog.DialogHelper;
import com.yunshipei.ui.fragment.GroupAvatarFragment;
import com.yunshipei.ui.fragment.GroupMemberFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.rong.app.DemoContext;
import io.rong.app.model.GroupCreateInfo;
import io.rong.app.ui.LoadingDialog;
import io.rong.app.utils.Constants;
import io.rong.app.utils.StringUtilSub;
import io.rong.eventbus.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;

/**
 * Created by cike on 15-9-22.
 */
public class GroupMainPageActivity extends BaseActivity implements View.OnClickListener {
    private static final int REQUESTCODE = 2;
    private static final int REQUESTDELETE = 3;
    public static final String GID = "gid";
    public static final String GROUPNAME = "group_name";
    public static final String ALL_GROUP = "ysp_group_all";
    private int gridSize = 18;
    private boolean groupState = true;
    private GroupCreateInfo mApiResult;
    private LoadingDialog mDialog;
    private SharedPreferences mySharedPreferences;
    private TextView groupMemberTotal, groupName;
    private TextView quitLayout;
    private LinearLayout searchMessage;
    private LinearLayout changeGroupName;
    private ScrollView scrollView;
    private DatabaseUtil dataUtil;
    private String groupCreateId;
    private YspTitleBar mTitleBar;
    private GroupAvatarFragment mFragment;
    private GroupMemberFragment groupMemberFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.group_main_page);
        mySharedPreferences = getSharedPreferences("ysp_rongCloud", Activity.MODE_PRIVATE);
        initView();
        initData();
    }

    protected void initView() {
        mTitleBar = (YspTitleBar) findViewById(R.id.title_bar);
        mTitleBar.setTitle("会话设置");
        changeGroupName = (LinearLayout) findViewById(R.id.change_group_name);
        mDialog = new LoadingDialog(this);
        scrollView = (ScrollView) findViewById(R.id.src);
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                scrollView.scrollTo(0, 0);
            }
        });
        groupMemberTotal = (TextView) findViewById(R.id.group_member_total);
        groupName = (TextView) findViewById(R.id.group_name);
        quitLayout = (TextView) findViewById(R.id.group_quit);
        searchMessage = (LinearLayout) findViewById(R.id.search_messges);
        changeGroupName.setOnClickListener(this);
        groupMemberTotal.setOnClickListener(this);
        quitLayout.setOnClickListener(this);
        searchMessage.setOnClickListener(this);
        mFragment = (GroupAvatarFragment) getFragmentManager().findFragmentById(R.id.avatar_fragment);
        groupMemberFragment = (GroupMemberFragment) getFragmentManager().findFragmentById(R.id.group_member);
    }

    protected void initData() {
        if (DemoContext.getInstance(GroupMainPageActivity.this) != null) {
            if (getIntent().hasExtra("INTENT_GROUP")) {
                mApiResult = (GroupCreateInfo) getIntent().getSerializableExtra("INTENT_GROUP");
                mFragment.setmApiResult(mApiResult);
                groupMemberFragment.setGroupCreateInfo(mApiResult);
                groupCreateId = mApiResult.getCreate_user_id();
                //判断群主状态
                if (groupCreateId != null && groupCreateId.equals(mySharedPreferences.getString("uuid", ""))) {
                    groupState = true;
                } else {
                    groupState = false;
                }
            }
            if (mApiResult != null) {
                groupName.setText(StringUtilSub.getInstance().SubStringAddCH(0, mApiResult.getName().toString(), 10));
                groupMemberTotal.setText("全部群成员(" + mApiResult.getNumber() + ")");
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
            case R.id.upClass:
                finish();
                break;
            case R.id.change_group_name:
                changeGroupName();
                break;
            case R.id.group_member_total:
                allGroup();
                break;
            case R.id.group_quit:
                DialogHelper.showQuitGroup(GroupMainPageActivity.this, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        quitGroup(true, mySharedPreferences.getString("uuid", ""), new QuitGroupSubscriber());
                    }
                });
                break;
            case R.id.search_messges:
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("groupInfo", mApiResult);
                intent.putExtra("groupInfo", bundle);
                intent.setClass(this, SearchGroupMessageActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private void changeGroupName() {
        Intent intent = new Intent(this, RefreshGroupNameActivity.class);
        intent.putExtra(this.GID, mApiResult.getId());
        intent.putExtra(this.GROUPNAME, mApiResult.getName());
        startActivityForResult(intent, REQUESTCODE);
    }

    private void allGroup() {
        Intent seekIntent = new Intent(ALL_GROUP);
        seekIntent.putExtra("groupAcount", mApiResult.getNumber());
        seekIntent.putExtra("groupMembers", mApiResult.getGourpMembers());
        seekIntent.setClass(this, SeekContactsActivity.class);
        startActivity(seekIntent);
    }

    public void quitGroup(boolean isActive, String quitUuid, BaseSubscriberAdapter<JSONObject> baseSubscriber) {
        if (DemoContext.getInstance(GroupMainPageActivity.this) != null) {
            if (mDialog != null && !mDialog.isShowing())
                mDialog.show();
            HttpMethods.getInstance().quitIMGroup(isActive, mySharedPreferences.getString("companyId", ""), quitUuid, mApiResult.getId(), baseSubscriber);
        }
    }

    private class QuitGroupSubscriber extends BaseSubscriberAdapter<JSONObject> {

        @Override
        public void onNext(JSONObject jsonObject) {
            mDialog.dismiss();
            try {
                if (jsonObject.getInt("status") == 1) {
                    Map<String, Group> groupMap = DemoContext.getInstance(GroupMainPageActivity.this).getGroupMap();
                    Map<String, Group> groupMapClone = new HashMap<String, Group>();
                    List<GroupCreateInfo> mResultList = DemoContext.getInstance(GroupMainPageActivity.this).getResult();
                    for (Map.Entry<String, Group> entry : groupMap.entrySet()) {
                        if (!entry.getValue().getId().equals(mApiResult.getId())) {
                            groupMapClone.put(entry.getValue().getId(), entry.getValue());
                        }
                    }
                    List<GroupCreateInfo> newResultList = new ArrayList<GroupCreateInfo>();
                    for (GroupCreateInfo groupCI : mResultList) {
                        if (!groupCI.getId().equals(mApiResult.getId())) {
                            newResultList.add(groupCI);
                        }
                    }
                    DemoContext.getInstance(GroupMainPageActivity.this).setGroupMap(groupMapClone);
                    DemoContext.getInstance(GroupMainPageActivity.this).setResult(newResultList);
                    EventBus.getDefault().post(1);
                    RongIM.getInstance().getRongIMClient().removeConversation(Conversation.ConversationType.GROUP, mApiResult.getId());
                    RongIM.getInstance().clearMessages(Conversation.ConversationType.GROUP, mApiResult.getId());
                    (new DatabaseUtil()).delateGroup(mApiResult.getId());
//                    mDialog.dismiss();
                    Intent intent = new Intent();
                    setResult(Constants.GROUP_QUIT_REQUESTCODE, intent);
                    finish();
                } else if (jsonObject.optInt("status", 0) == 0) {
//                    mDialog.dismiss();
                    Toast.makeText(GroupMainPageActivity.this, jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(String errorMessage) {
            mDialog.dismiss();
            Toast.makeText(GroupMainPageActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
        }
    }

    /*
    获取群组成员列表
     */
    public List<HeadName> getAvatarList(String originalStr, String groupCreateId) {
        List<HeadName> list = new ArrayList<>();
        dataUtil = new DatabaseUtil();
        try {
            JSONArray groupMemIdArray = new JSONArray(originalStr);
            int length = groupMemIdArray.length();
            if (gridSize != 0 && length > gridSize) {
                length = gridSize;
            }
            for (int i = 0; i < length; i++) {
                HeadName hName = new HeadName();
                io.rong.imlib.model.UserInfo userInfo = dataUtil.queryByUuid(groupMemIdArray.getString(i));
                if (userInfo != null) {
                    hName.setUuid(userInfo.getUserId());
                    hName.setName(userInfo.getName());
                    if (userInfo.getPortraitUri() != null) {
                        hName.setAvatarUri(userInfo.getPortraitUri().toString());
                    }
                    if (!TextUtils.isEmpty(userInfo.getUserId()) && userInfo.getUserId().equals(groupCreateId)) {
                        list.add(0, hName);
                    } else {
                        list.add(hName);
                    }
                } else {
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return list;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String result;
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == this.REQUESTCODE && resultCode == RefreshGroupNameActivity.RESULTCODE) {
            String groupNameStr = data.getStringExtra(RefreshGroupNameActivity.NEWGROUPNAME);
            groupName.setText(StringUtilSub.getInstance().SubStringAddCH(0, groupNameStr, 8));
            setGroupName(groupNameStr);
            DemoContext.getInstance(GroupMainPageActivity.this).updateGroupInfoById(mApiResult.getId(), groupNameStr, DemoContext.STATE2);
            EventBus.getDefault().post(new EventModelObject(groupNameStr));
            refreshGroupInfo(new Group(mApiResult.getId(), mApiResult.getName(), Uri.parse(mApiResult.getPortraitUri())));
        } else if (requestCode == this.REQUESTDELETE) {
        }
    }

    public void setGroupName(String groupNameStr) {
        mApiResult.setName(groupNameStr);
        mFragment.setGroupName(groupNameStr);
    }

    /**
     * 添加了用户缓存更新方法(rongcloud)
     */
    private void refreshGroupInfo(Group group) {

        if (group == null) {
            throw new IllegalArgumentException();
        }

        if (RongIM.getInstance() != null) {
            RongIM.getInstance().refreshGroupInfoCache(group);
        }
    }

    /**
     * 限定GridView显示
     *
     * @param MaxSize
     */
    public void setGridSize(int MaxSize) {
        this.gridSize = MaxSize;
    }

    /**
     * 自己被删除出群
     *
     * @param clearGroupNumber
     */
    public void onEventMainThread(ClearGroupNumber clearGroupNumber) {
        if (clearGroupNumber != null && clearGroupNumber.getUserId().equals(mySharedPreferences.getString("uuid", ""))) {
            Intent intent = new Intent();
            intent.setClass(GroupMainPageActivity.this, DemoActivity.class);
            setResult(Constants.GROUP_QUIT_REQUESTCODE, intent);
            this.finish();
        }
    }

    public void setGroupNember(int size) {
        groupMemberTotal.setText("全部群成员(" + size + ")");
    }

    public void setGroupCreateInfo(GroupCreateInfo groupCreateInfo) {
        this.mApiResult = groupCreateInfo;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
